import React, { Component } from 'react';
import { Affix, Button, Spin, Icon, Menu, Col, Card, Tooltip, Modal } from 'antd';
import 'styles/data-center/report-management/custom-report/graph.scss';
import { messages } from 'share/common';
import {
  commonBarReportFactory,
  commonPieReportFactory,
  commonLineReportFactory,
  commonAreaReportFactory,
  commonRadarReportFactory
} from 'containers/data-center/report-management/custom-report/graphic/echarts-data-transfer';
import CustomReportService
  from 'containers/data-center/report-management/custom-report/custom-report.service';

import Charts from 'components/template/graphic-report/report-echarts';
import IndexGraphic
  from 'containers/data-center/report-management/custom-report/graphic/index-graphic';
import IndexTable from 'containers/data-center/report-management/custom-report/graphic/index-table';

import Condition from 'components/condition';

const { If, Else } = Condition;
import { ImgMap } from 'containers/data-center/report-management/custom-report/custom-report.modal';
import ExportModal from 'components/template/export-modal/export-modal';
import debounce from 'lodash.debounce';


class Graphic extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataLength: 0,
      isFetchingData: false,
      isLoading: false,
      options: {},
      data: [],
      chartOutOfService: false,
      failedGetData: false,
      showMyModal: false
    };
    this.fetchData = debounce(this.fetchData, 300);
  }

  shouldComponentUpdate(nextProps, nextState, nextContext) {
    return !nextProps.shouldUpdate;
  }

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
    this.initMe();
  }

  initMe = () => {
    const { widget, searchParamsData, isPreView } = this.props;
    if (widget.set && !(['detail_list', 'perspective'].indexOf(widget.key) !== -1)) { //设置过的 就 获取data
      this.fetchData(widget, searchParamsData, isPreView);
    } else if (widget.set && ['detail_list', 'perspective'].indexOf(widget.key) !== -1) {
      this.fetchTableData();
    }
  }

  compareValue = (newSearchParamsData, newChartLinkableParams, searchParamsData, chartLinkableParams) => {
    let searchParamsResult = false,
      LinkableParamsResult = false;
    if (newChartLinkableParams.length === chartLinkableParams.length) {
      if (chartLinkableParams.length !== 0 && newChartLinkableParams.length !== 0) {
        if ((newChartLinkableParams && newChartLinkableParams[0] && newChartLinkableParams[0].values && newChartLinkableParams[0].values[0].value) !== (chartLinkableParams && chartLinkableParams[0] && chartLinkableParams[0].values && chartLinkableParams[0].values[0].value)) {
          LinkableParamsResult = true;
        }
      }
    } else {
      LinkableParamsResult = true;
    }
    if (newSearchParamsData.length === searchParamsData.length) {
      if (newSearchParamsData.length !== 0 && searchParamsData.length !== 0) {
        newSearchParamsData.forEach((item, newIndex) => {
          if (item.values.length === searchParamsData[newIndex].values.length) {
            item.values.forEach((newValue, newValueIndex) => {
              if (newValue.value !== searchParamsData[newIndex].values[newValueIndex].value) {
                searchParamsResult = true;
              }
            });
          } else {
            searchParamsResult = true;
          }
        });
      }
    } else {
      searchParamsResult = true;
    }
    // console.log('情况：', searchParamsResult, LinkableParamsResult)
    return (searchParamsResult || LinkableParamsResult);
  };

  componentWillReceiveProps(nextProps, nextContext) {
    if (!nextProps.noRefresh) {
      if (nextProps.forceRefresh) {
        this.fetchAllDataFunc(nextProps);
      } else {
        const { searchParamsData, chartLinkableParams } = this.props;
        if (this.compareValue(nextProps.searchParamsData, nextProps.chartLinkableParams, searchParamsData, chartLinkableParams)) {
          this.fetchAllDataFunc(nextProps);
        }
      }
    } else {
      this.setState({options: this.handleOptions(this.state.data, nextProps.widget)})
    }
  }

  fetchAllDataFunc = (nextProps) => {
    if (!(['detail_list', 'perspective'].indexOf(nextProps.widget.key) !== -1)) {
      this.fetchData(nextProps.widget, nextProps.searchParamsData.concat(nextProps.chartLinkableParams), nextProps.isPreView, nextProps.isManualSearch);
    } else if (['detail_list', 'perspective'].indexOf(nextProps.widget.key) !== -1) {
      this.fetchTableData();
    }
  }

  fetchTableData = (modal) => {
    if (modal) {
      this.modalIndexTableRef && this.modalIndexTableRef.willReload();
    } else {
      this.IndexTableRef && this.IndexTableRef.willReload();
    }
  };

  fetchData = (widget, params, isPreView, isManualSearch) => {
    this.setState({ isLoading: true, failedGetData: false });
    let promiseData = CustomReportService.getSingleChartData(
      widget.reportId,
      widget.id,
      0,
      widget.limitNum || 10000,
      isPreView,
      isManualSearch,
      params || []
    )
      .then((res) => {
        if (res.status === 200) {
          this.setState({
            options: this.handleOptions(res.data, widget),
            isLoading: false,
            data: res.data,
            dataLength: res.data.length
          });
        }
      })
      .catch(() => {
        this.setState({ isLoading: false, failedGetData: true });
      });
    this.props.handleOverPromise && this.props.handleOverPromise(promiseData);
  };

  handleOptions = (data, widget) => {
    let GraphicType = widget.key;
    let options = {};
    switch (GraphicType) {
      case 'indicatrix' :
        options = { data, labelAndValue: this.handleLabelAndValue(widget), widget };
        break;
      case 'histogram' :
        options = commonBarReportFactory(data, this.handleLabelAndValue(), false, widget);
        break;
      case 'horizon-histogram' :
        options = commonBarReportFactory(data, this.handleLabelAndValue(), true, widget);
        break;
      case 'area' :
        options = commonAreaReportFactory(data, this.handleLabelAndValue(), widget);
        break;
      case 'broken_line' :
        options = commonLineReportFactory(data, this.handleLabelAndValue(), widget);
        break;
      case 'pie' :
        options = commonPieReportFactory(data, ['left', 'right'].indexOf(widget.showLegendLocation) !== -1, this.handleLabelAndValue(), '', widget);
        break;
      case 'radar' :
        options = commonRadarReportFactory(data, this.handleLabelAndValue(), widget);
        break;
    }
    return options;
  };

  handleLabelAndValue = (nextWidget) => {
    const { widget, noCard, selectDimensionDataList, selectIndicatorDataList } = this.props;
    let result = {
      dimension: {},
      indicator: []
    };
    let target = nextWidget || widget;
    if (target.set) {
      if (noCard) {
        selectDimensionDataList.forEach((item) => {
          result.dimension.code = item.columnPropName;
          result.dimension.name = item.fieldDisplayName || item.columnDisplayName;
        });
        selectIndicatorDataList.forEach((item) => {
          result.indicator.push({
            code: item.columnPropName,
            name: item.fieldDisplayName || item.columnDisplayName
          });
        });
      } else {
        target.reportChartDetails && target.reportChartDetails.forEach((item) => {
          if (item.fieldType === 'dimension') {
            result.dimension.code = item.columnPropName;
            result.dimension.name = item.fieldDisplayName || item.columnDisplayName;
          } else {
            result.indicator.push({
              code: item.columnPropName,
              name: item.fieldDisplayName || item.columnDisplayName
            });
          }
        });
      }
      return result;
    } else {
      return result;
    }
  };

  onChartClick = ({ item, chartIndex, reportKey, active }) => {
    this.props.onChartClick && this.props.onChartClick({
      item,
      chartIndex,
      reportKey,
      active
    }, this.props.widget.sourceReportId);
  };

  showMyModal = () => {
    this.setState({ showMyModal: true }, () => {
      this.fetchTableData(true);
    });
  };

  hideMyModal = () => {
    this.setState({ showMyModal: false });
  };

  onChartOutOfService = () => {
    this.setState({chartOutOfService: true});
  }

  render() {
    const { isLoading, options, dataLength, showMyModal, failedGetData, chartOutOfService } = this.state;
    const {
      widget, fakeDataLength, fakeData, noCard, selectShowDataList, noEdit, searchParamsData, chartLinkableParams,
      isPreView, displayMode, selectDimensionDataList, selectIndicatorDataList, changingScreen, isFetchingData,
      selectDimensionRowDataList
    } = this.props;
    const selectBoth = selectDimensionDataList && selectDimensionDataList.length >= 1 && selectIndicatorDataList && selectIndicatorDataList.length >= 1;
    const extra = (<div className="extra-operation">
      {!noEdit ? <span>
        <Tooltip
          title={widget.set ? (widget.showScreen === 'half' ? messages('basic-10.key165')/*全屏*/ : messages('basic-10.key166')/*半屏*/) : messages('basic-10.key167')/*编辑保存后即可切换*/}>
          {!changingScreen && <svg
            width="14px"
            height="14px"
            viewBox="0 0 14 14"
            version="1.1"
            className={`icon ${widget.set ? '' : 'disabled'}`}
            onClick={(e) => {
              widget.set && this.props.onStretchItem(widget);
            }}
          >
            {widget.showScreen === 'all' &&
            <path
              d="M12.5,0.5 C13.0522847,0.5 13.5,0.94771525 13.5,1.5 L13.5,12.5 C13.5,13.0522847 13.0522847,13.5 12.5,13.5 L1.5,13.5 C0.94771525,13.5 0.5,13.0522847 0.5,12.5 L0.5,1.5 C0.5,0.94771525 0.94771525,0.5 1.5,0.5 L12.5,0.5 Z M12.5,1.5 L1.5,1.5 L1.5,12.5 L12.5,12.5 L12.5,1.5 Z M10.3535534,4.64644661 L11.0606602,5.35355339 L9.41398974,7.00021547 L11.0606602,8.64644661 L10.3535534,9.35355339 L8,7 L10.3535534,4.64644661 Z M3.70710678,4.64644661 L6.06066017,7 L3.70710678,9.35355339 L3,8.64644661 L4.64667043,6.99978453 L3,5.35355339 L3.70710678,4.64644661 Z"/>
            }
            {widget.showScreen === 'half' &&
            <path
              d="M12.5,0.5 C13.0522847,0.5 13.5,0.94771525 13.5,1.5 L13.5,12.5 C13.5,13.0522847 13.0522847,13.5 12.5,13.5 L1.5,13.5 C0.94771525,13.5 0.5,13.0522847 0.5,12.5 L0.5,1.5 C0.5,0.94771525 0.94771525,0.5 1.5,0.5 L12.5,0.5 Z M12.5,1.5 L1.5,1.5 L1.5,12.5 L12.5,12.5 L12.5,1.5 Z M5.35355339,4.64644661 L6.06066017,5.35355339 L4.41410678,7 L6.06066017,8.64644661 L5.35355339,9.35355339 L3,7 L5.35355339,4.64644661 Z M8.70710678,4.64644661 L11.0606602,7 L8.70710678,9.35355339 L8,8.64644661 L9.64655339,7 L8,5.35355339 L8.70710678,4.64644661 Z"/>
            }
          </svg>}
          {changingScreen && <Icon type="loading" style={{ margin: '0 4px' }}/>}
        </Tooltip>
        <Tooltip title={messages('common.delete')/*删除*/}>
        <svg
          width="14px"
          height="14px"
          viewBox="0 0 14 14"
          version="1.1"
          className='icon delete'
          onClick={(e) => {
            e.stopPropagation();
            this.props.onDeleteItem(widget);
          }}
        >
        <path
          d="M9,0.5 C9.77969612,0.5 10.4204487,1.09488808 10.4931334,1.85553999 L10.5,2 L10.5,3 L13.5,3 L13.5,4 L12.452,4 L11.4524938,14 L2.54750622,14 L1.547,4 L0.5,4 L0.5,3 L3.5,3 L3.5,2 C3.5,1.22030388 4.09488808,0.579551322 4.85553999,0.506866578 L5,0.5 L9,0.5 Z M11.447,4 L2.552,4 L3.452,13 L10.547,13 L11.447,4 Z M6,5.5 L6,11 L5,11 L5,5.5 L6,5.5 Z M9,5.5 L9,11 L8,11 L8,5.5 L9,5.5 Z M9,1.5 L5,1.5 C4.75454011,1.5 4.55039163,1.67687516 4.50805567,1.91012437 L4.5,2 L4.5,3 L9.5,3 L9.5,2 C9.5,1.75454011 9.32312484,1.55039163 9.08987563,1.50805567 L9,1.5 Z"/>
        </svg>
        </Tooltip>
        <Tooltip title={messages('common.edit')/*编辑*/}>
        <svg
          width="14px"
          height="14px"
          viewBox="0 0 14 14"
          version="1.1"
          className='icon'
          onClick={(e) => {
            e.stopPropagation();
            this.props.onEditItem(widget);
          }}
        >
        <path
          d="M13.5,12.5 L13.5,13.5 L0.5,13.5 L0.5,12.5 L13.5,12.5 Z M9.89918912,1.25882321 C10.5386771,0.732186076 11.4840082,0.823669736 12.0106454,1.46315768 L12.0106454,1.46315768 L12.7745374,2.41778127 C13.2868691,3.05819583 13.1898789,3.99135609 12.5567951,4.51271919 L12.5567951,4.51271919 L4.6793827,11 L1.39009805,11 L2.04464355,7.7272725 Z M9.298,3.04767614 L2.955,8.271 L2.61,10 L4.32,10 L10.674,4.76767614 L9.298,3.04767614 Z M11.1753621,2.03460826 C10.9944035,1.88146943 10.7243743,1.87471281 10.5348964,2.03075344 L10.5348964,2.03075344 L10.07,2.41267614 L11.446,4.13167614 L11.9210879,3.74078896 C12.0852207,3.60562075 12.1412523,3.38741525 12.077698,3.19667004 L12.0431054,3.11692549 L11.9936686,3.04247632 L11.2431844,2.10437104 Z"/>
        </svg>
        </Tooltip>
      </span> : null}
      {noEdit &&
      <div className='display-operation-area'>
        {['detail_list', 'perspective'].indexOf(widget.key) !== -1 && widget.operateType === 'true' &&
        <div className='operate-btn'>
          <ExportModal
            // style={config.style}
            type={'icon'}
            btnType={'primary'}
            codeCheck={true}
            disabled={chartOutOfService}
            clickPropagationEnable
            exportTitle={chartOutOfService ? messages('basic-10.key168')/*超过服务上限，无法导出*/ : messages('basic-10.key169')/*导出数据*/}
            exportType="USER_DEFINE_CHART_REPORT"
            customExport
            reportId={widget.reportId}
            reportChartId={widget.id}
            userDefineReportSearchDTOS={searchParamsData}
            exportCondition={{
              'command': 'USER_DEFINE',
              'exportType': 'USER_DEFINE',
              'reportSearchDTO': {},
              // 'expenseAnalysisRequestEntity': transParams,
            }}
            exportCommand={'USER_DEFINE'}
          />
        </div>
        }
        <div className="operate-btn" onClick={this.showMyModal}>
          <Tooltip title={messages('basic-10.key170')/*放大元素查看*/}>
            <svg
              width="14px"
              height="14px"
              viewBox="0 0 14 14"
              version="1.1"
              className='icon full-icon'
            >
              <path
                d="M5.64644661,7.64644661 L6.35355339,8.35355339 L2.706,12 L6,12 L6,13 L1,13 L1,8 L2,8 L2,11.292 L5.64644661,7.64644661 Z M13,1 L13,6 L12,6 L12,2.706 L8.35355339,6.35355339 L7.64644661,5.64644661 L11.292,2 L8,2 L8,1 L13,1 Z"
                id="ICON_最大化"/>
            </svg>
          </Tooltip>
        </div>
      </div>
      }
    </div>);

    const fakeOptions = this.handleOptions(fakeData || [], widget);

    return (
      <div className="graph-wrapper">
        <Condition>
          <If value={!noCard}>
            <Card title={widget.name || widget.chartName} bordered={false} extra={extra}>
              <Condition>
                <If value={widget.set}>
                  {!(['indicatrix', 'detail_list', 'perspective'].indexOf(widget.key) !== -1) &&
                  <Charts
                    allowActivated={widget.key !== 'radar'}
                    cols={24}
                    compareUpdate={noEdit}
                    customCols={widget.showScreen === 'half' ? 12 : 24}
                    dataLength={dataLength}
                    options={options}
                    height={335}
                    isFetchingData={isFetchingData}
                    loading={isLoading}
                    failedGetData={failedGetData}
                    waterMark={noEdit}
                    reportType={`custom-${widget.key}`}
                    compareKey={widget.reportChartDetails && widget.reportChartDetails.filter(item => item.fieldType === 'dimension').length !== 0 && widget.reportChartDetails.filter(item => item.fieldType === 'dimension')[0].linkageColumnPropName}
                    displayMode={displayMode}
                    onRef={ref => this.onMountCharts = ref}
                    reportKey={widget.id}
                    onActivatedItemChange={this.onChartClick}
                  />
                  }
                  {widget.key === 'indicatrix' &&
                  <IndexGraphic loading={isLoading} options={options} dataLength={dataLength}/>
                  }
                  {['detail_list', 'perspective'].indexOf(widget.key) !== -1 &&
                  <IndexTable
                    widget={widget}
                    isPreView={isPreView}
                    onRef={ref => this.IndexTableRef = ref}
                    handleOverPromise={this.props.handleOverPromise}
                    onOutOfService={this.onChartOutOfService}
                    chartLinkableParams={chartLinkableParams}
                    searchParamsData={searchParamsData}
                  />
                  }
                </If>
                <Else>
                  <div className='unset-chart'>
                    <img onMouseDown={e => e.preventDefault()} className='unset-img'
                         src={ImgMap[widget.key]}/>
                    <div
                      onClick={(e) => {
                        e.stopPropagation();
                        this.props.onEditItem(widget);
                      }}
                      className="tips"
                    >
                      {messages('basic-10.key171')/*编辑图表*/} <Icon type="right"/>
                    </div>
                  </div>
                </Else>
              </Condition>
            </Card>
          </If>
          <Else>
            {!(['indicatrix', 'detail_list', 'perspective'].indexOf(widget.key) !== -1) && selectBoth &&
            <Charts
              title={widget.name}
              cols={24}
              customCols={20}
              height={350}
              dataLength={fakeDataLength}
              options={fakeOptions}
              isFetchingData={isFetchingData}
              loading={isLoading}
              waterMark={false}
              onRef={ref => this.onMountCharts = ref}
            />
            }
            {(widget.key !== 'indicatrix' && widget.key !== 'detail_list') && !selectBoth &&
            <div className='place-holder'>{messages('basic-10.key172')/*请选择维度与指标*/}</div>
            }
            {widget.key === 'indicatrix' &&
            <IndexGraphic
              loading={isLoading}
              dataLength={fakeDataLength}
              options={fakeOptions}
            />
            }
            {['detail_list', 'perspective'].indexOf(widget.key) !== -1 &&
            <IndexTable
              widget={widget}
              onRef={ref => this.IndexTableRef = ref}
              data={fakeData}
              onOutOfService={this.onChartOutOfService}
              selectIndicatorDataList={selectIndicatorDataList}
              selectDimensionRowDataList={selectDimensionRowDataList}
              selectDimensionDataList={selectDimensionDataList}
              selectShowDataList={selectShowDataList}
            />
            }
          </Else>
        </Condition>
        <Modal
          width='calc(100vw - 96px)'
          wrapClassName='custom-full-modal'
          title={widget.name}
          maskClosable={false}
          visible={showMyModal}
          centered
          zIndex={10000}
          footer={null}
          onCancel={this.hideMyModal}
          bodyStyle={{ height: 'calc(100vh - 151px)' }}
        >
          {!(['indicatrix', 'detail_list', 'perspective'].indexOf(widget.key) !== -1) &&
          <Charts
            fullScreenMode={true}
            cols={24}
            customCols={widget.showScreen === 'half' ? 12 : 24}
            dataLength={dataLength}
            options={options}
            height={'calc(100vh - 311px)'}
            isFetchingData={isFetchingData}
            loading={isLoading}
            failedGetData={failedGetData}
            waterMark={true}
            onRef={ref => this.onMountChartsModal = ref}
            onActivatedItemChange={this.onChartClick}
          />
          }
          {widget.key === 'indicatrix' &&
          <IndexGraphic
            fullScreenMode={true}
            loading={isLoading}
            options={options}
            dataLength={dataLength}
            searchParamsData={searchParamsData}
            chartLinkableParams={chartLinkableParams}
          />
          }
          {['detail_list', 'perspective'].indexOf(widget.key) !== -1 &&
          <IndexTable
            fullScreenMode={true}
            widget={widget}
            handleOverPromise={this.props.handleOverPromise}
            onRef={ref => this.modalIndexTableRef = ref}
            onOutOfService={this.onChartOutOfService}
            isPreView={isPreView}
            searchParamsData={searchParamsData}
            chartLinkableParams={chartLinkableParams}
          />
          }
        </Modal>
      </div>
    );
  }
}

Graphic.propTypes = {
  isNew: React.PropTypes.boolean, // 是否为新增的空表
  title: React.PropTypes.string,
  width: React.PropTypes.string, // full为通栏，否则为半栏
  type: React.PropTypes.string, // 图表类型，折线图 | 雷达图等
  conditions: React.PropTypes.array || React.PropTypes.object, // 维度、指标、模型等等，用来获取数据
  onEditItem: React.PropTypes.func, // 点击编辑
  onDeleteItem: React.PropTypes.func, // 点击删除，这个可以组件内消化
  onStretchItem: React.PropTypes.func, // 点击宽度变化
  selectShowDataList: React.PropTypes.array
};
Graphic.defaultprops = {
  isNew: false,
  selectShowDataList: []
};

export default Graphic;
